<?php 

if( !defined('CORE_PATH')) die("Access Denied");

class File extends Helper {


	public function __construct() {
		
	}
	
	/**
     * Uploads a single file to the server
     */
    function uploadFile($dirname = NULL, $filename = NULL, $mime_types = NULL) {
		
		if( isset($_FILES['uploadfile']) && is_array($_FILES['uploadfile']['name']) ) {
			return $this->uploadFiles($dirname, $filename, $mime_types);
		}
		
        $fileType = $_FILES['uploadfile']['type'];

        # list of permitted file types, this is only images but documents can be added
        //$permitted = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/svg+xml');

        $typeOk = true; # with the correct type the file will be uploaded or rejected.

        /*foreach ($permitted as $type) {
            if ($type == $fileType) {
                $typeOk = true;
                break;
            }
        }*/
		
        # if typeOk upload the file
        if ($typeOk) {
			
            if( isset($dirname) && $dirname != "" ) {
    			
				// attempt to create the target directory if it does not exist
				@mkdir($dirname, 0775, true);
				
				// check if the directory was created or already exists
				if( file_exists($dirname) ) {
					// throw if directory is not writable
					if( !is_writable($dirname) ) {
						return array('type' => 'error', 'message' => 'Upload Directory Is Not Writable');
					}
					
					// determine the extension of the uploaded file
					$ext = substr($_FILES['uploadfile']['name'], strrpos($_FILES['uploadfile']['name'], "."));
					
					// append the file extension if not already part of the uploaded file name
					if( stristr($filename, $ext) === FALSE ) {
						$filename = $filename . $ext;
					}
					
					// determine the name of the destination file
					$destName = is_string($filename) && $filename != "" ? $dirname . $filename : $dirname . $_FILES['uploadfile']['name'];

					// if already present inform
					if( file_exists($destName) ) {
						return array('type' => 'error', 'message' => 'File Already Exists');
					}
					
					// upload move uploaded file to destination
					else {
						move_uploaded_file($_FILES['uploadfile']['tmp_name'], $destName );
					}
					
					// inform of success
					return array('type' => 'success', 'file' => $destName, 'fileType' => $fileType);
				}
				
				else {
					return array('type' => 'error', 'message' => 'Upload Directory Does Not Exist');	
				}
				
            } else {
				// get the file data
	            $file_contents = file_get_contents($_FILES['uploadfile']['tmp_name']);
                return array('type' => 'success', 'data' => $file_contents, 'file_type' => $fileType);
            }
        }

        return false;
    }
	
	/**
     * Uploads Multiple Files to the servers
     */
    function uploadFiles($dirname = NULL, $filename_orig = NULL, $mime_types = NULL) {

        # list of permitted file types, this is only images but documents can be added
        //$permitted = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/svg+xml');
			
		if( isset($dirname) && $dirname != "" ) {
			
			// attempt to create the target directory if it does not exist
			@mkdir($dirname, 0775, true);
			
			// check if the directory was created or already exists
			if( file_exists($dirname) ) {
				// throw if directory is not writable
				if( !is_writable($dirname) ) {
					return array('type' => 'error', 'message' => 'Upload Directory Is Not Writable');
				}
				
				// get number of uploaded files
				$uploaded = count($_FILES['uploadfile']['name']);
				$files = array();
				
				for($i = 0; $i < $uploaded; $i++) {
					
					$fileType = $_FILES['uploadfile']['type'][$i];
					
					$typeOk = true; # with the correct type the file will be uploaded or rejected.

					# if typeOk upload the file
					if ($typeOk) {
						
						// determine the extension of the uploaded file
						$ext = substr($_FILES['uploadfile']['name'][$i], strrpos($_FILES['uploadfile']['name'][$i], "."));
						$filename = isset($filename_orig) ? $filename_orig : $_FILES['uploadfile']['name'][$i];
						
						// append the file extension if not already part of the uploaded file name
						if( stristr($filename, $ext) === FALSE ) {
							$filename = $filename . "_$i" . $ext;
						}
						
						// determine the name of the destination file
						$destName = is_string($filename) && $filename != "" ? ($dirname . $filename) : $dirname . $_FILES['uploadfile']['name'][$i];
	
						// if already present inform
						if( !file_exists($destName) ) {
							move_uploaded_file($_FILES['uploadfile']['tmp_name'][$i], $destName );
							$files[] = array(
                                'file_name' => $destName,
                                'mime_type' => $fileType
                            );
						}
					}
				}
				
				// inform of success
				return array('type' => 'success', 'files' => $files);
			}
			
			else {
				return array('type' => 'error', 'message' => 'Upload Directory Does Not Exist');	
			}
        }

        return false;
    }
	
	public function deleteFile($file) {
		
		if( !file_exists($file) ) {
			return;	
		}
		
		try {
			unlink($file);
		} catch(Exception $e) {
			echo $e;
		}
	}
	
	public function deleteDirectory($dirname) {
	   // Sanity check
	   if (!file_exists($dirname) ) {
		  return false;
	   }
	
	   // Simple delete for a file
	   if (is_file($dirname)) {
		  return unlink($dirname);
	   }
	
	   // Loop through the folder
	   $dir = dir($dirname);
	   while (false !== $entry = $dir->read()) {
		  // Skip pointers
		  if ($entry == '.' || $entry == '..') {
			 continue;
		  }
	
		  // Recurse
		  $this->deleteDirectory("$dirname/$entry");
	   }
	
	   // Clean up
	   $dir->close();
	   return rmdir($dirname);
	}
	
	public function extractZipArchive($filePath, $destFolder = '') {
		// create object
		$zip = new ZipArchive() ;
		
		// open archive
		if ($zip->open( $filePath ) !== TRUE) {
			die ('Could not open archive');
		}
		
		// if the destFolder is not supplied, then we'll need to extract the file to
		// same directory.
		if( $destFolder == '') {
			$destFolder = dirname($filePath);	
		}
		
		// extract contents to destination directory
		$zip->extractTo($destFolder);
		
		// close archive
		$zip->close();   
   }
   
   /** 
     * Copy file or folder from source to destination, it can do 
     * recursive copy as well and is very smart 
     * It recursively creates the dest file or directory path if there weren't exists 
     * Situtaions : 
     * - Src:/home/test/file.txt ,Dst:/home/test/b ,Result:/home/test/b -> If source was file copy file.txt name with b as name to destination 
     * - Src:/home/test/file.txt ,Dst:/home/test/b/ ,Result:/home/test/b/file.txt -> If source was file Creates b directory if does not exsits and copy file.txt into it 
     * - Src:/home/test ,Dst:/home/ ,Result:/home/test/** -> If source was directory copy test directory and all of its content into dest      
     * - Src:/home/test/ ,Dst:/home/ ,Result:/home/**-> if source was direcotry copy its content to dest 
     * - Src:/home/test ,Dst:/home/test2 ,Result:/home/test2/** -> if source was directoy copy it and its content to dest with test2 as name 
     * - Src:/home/test/ ,Dst:/home/test2 ,Result:->/home/test2/** if source was directoy copy it and its content to dest with test2 as name 
     * @todo 
     *     - Should have rollback technique so it can undo the copy when it wasn't successful 
     *  - Auto destination technique should be possible to turn off 
     *  - Supporting callback function 
     *  - May prevent some issues on shared enviroments : http://us3.php.net/umask 
     * @param $source //file or folder 
     * @param $dest ///file or folder 
     * @param $options //folderPermission,filePermission 
     * @return boolean 
     */ 
   public function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755)) 
    { 
        $result=false; 
        
        if (is_file($source)) { 
            if ($dest[strlen($dest)-1]=='/') { 
                if (!file_exists($dest)) { 
                    cmfcDirectory::makeAll($dest,$options['folderPermission'],true); 
                } 
                $__dest=$dest."/".basename($source); 
            } else { 
                $__dest=$dest; 
            } 
            $result=copy($source, $__dest); 
            chmod($__dest,$options['filePermission']); 
            
        } elseif(is_dir($source)) { 
            if ($dest[strlen($dest)-1]=='/') { 
                if ($source[strlen($source)-1]=='/') { 
                    //Copy only contents 
                } else { 
                    //Change parent itself and its contents 
                    $dest=$dest.basename($source); 
                    @mkdir($dest); 
                    chmod($dest,$options['filePermission']); 
                } 
            } else { 
                if ($source[strlen($source)-1]=='/') { 
                    //Copy parent directory with new name and all its content 
                    @mkdir($dest,$options['folderPermission']); 
                    chmod($dest,$options['filePermission']); 
                } else { 
                    //Copy parent directory with new name and all its content 
                    @mkdir($dest,$options['folderPermission']); 
                    chmod($dest,$options['filePermission']); 
                } 
            } 

            $dirHandle=opendir($source); 
            while($file=readdir($dirHandle)) 
            { 
                if($file!="." && $file!="..") 
                { 
                     if(!is_dir($source."/".$file)) { 
                        $__dest=$dest."/".$file; 
                    } else { 
                        $__dest=$dest."/".$file; 
                    } 
                    //echo "$source/$file ||| $__dest<br />"; 
                    $result = $this->smartCopy($source."/".$file, $__dest, $options); 
                } 
            } 
            closedir($dirHandle); 
            
        } else { 
            $result=false; 
        } 
        return $result; 
    }
	
	public function encodeUrlParam ( $string ) {
	  $string = trim($string);
		
	  if ( ctype_digit($string) ) {
		return $string;
		
	  } else {      
		// replace accented chars
		$accents = '/&([A-Za-z]{1,2})(grave|acute|circ|cedil|uml|lig);/';
		$string_encoded = htmlentities($string,ENT_NOQUOTES,'UTF-8');
	
		$string = preg_replace($accents,'$1',$string_encoded);
		  
		// clean out the rest
		$replace = array('([\40])','([^a-zA-Z0-9-])','(-{2,})');
		$with = array('-','','-');
		$string = preg_replace($replace,$with,$string); 
	  } 
	
	  return strtolower($string);
	}

	function generateThumb( $imagePath, $outputDir, $thumbWidth = 150 ) {

		if( !file_exists($outputDir) && !mkdir($outputDir, 0777, true) ) {
		  return;
		}
		
		/*if( fileperms($outputDir) != 0777 ) {
		  @chmod($outputDir, 0777);
		}*/
		
		// get image file path information
		$info = pathinfo($imagePath);
		
		$img = NULL;
		// load image and get image size
		if ( strtolower($info['extension']) == 'jpg' ) {
		  $img = imagecreatefromjpeg( $imagePath );
		} else if ( strtolower($info['extension']) == 'gif' ) {
		  $img = imagecreatefromgif( $imagePath );
		} else if ( strtolower($info['extension']) == 'png' ) {
		  $img = imagecreatefrompng( $imagePath );
		}
		
		$width = imagesx( $img );
		$height = imagesy( $img );
		
		// calculate thumbnail size
		$new_width = $thumbWidth;
		$new_height = floor( $height * ( $thumbWidth / $width ) );
		
		
		if( $new_width < $width || $new_height < $height) {
		  // create a new temporary image
		  $tmp_img = imagecreatetruecolor( $new_width, $new_height );
		  
		  if ( strtolower($info['extension']) == 'png' ) {
			  // work on image transparency
			  imagealphablending($tmp_img, false);
			  imagesavealpha($tmp_img, true);
		  }
		
		  // copy and resize old image into new image
		  imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
		
		  // save thumbnail into a file
		  $fpath = "{$outputDir}{$info['basename']}";
		
		  if ( strtolower($info['extension']) == 'jpg' ) {
			 imagejpeg( $tmp_img, "{$outputDir}{$info['basename']}");
		  } else if ( strtolower($info['extension']) == 'gif' ) {
			 imagegif( $tmp_img, "{$outputDir}{$info['basename']}");
		  } else if ( strtolower($info['extension']) == 'png' ) { 
			 imagepng( $tmp_img, "{$outputDir}{$info['basename']}");
		  }
		
		  return $fpath;
		} else {
		  return $imagePath;
		}
	}
}
?>